//
//  main.c
//  StdRedict
//
//  Created by wangrui on 15-3-10.
//  Copyright (c) 2015年 wangrui. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

void error(char *msg) {
    fprintf(stderr, "%s: %s\n", msg, strerror(0));
    exit(1);
}

int main(int argc, const char * argv[]) {
    
    /*
     * system call
     *
    
    system("say 'My father was a self-taught mandolin player. He was one of \
           the best string instrument players in our town. He could not read \
           music, but if he heard a tune a few times, he could play it. \
           When he was younger, he was a member of a small country music band.'");
    
    printf("system call end! \n"); //阻塞,但会输出
     *
     */
    
    
    /*
     *
    //exec 系类函数会终止当前进程
     
    const char *argument0 = "My father was a self-taught mandolin player. He was one of \
    the best string instrument players in our town. He could not read \
    music, but if he heard a tune a few times, he could play it. \
    When he was younger, he was a member of a small country music band.";
    
    printf("%d \n",execl("/usr/bin/say", "say",argument0,NULL)); //语音一念完，程序就终止，没有输出。相当于一个接力赛一样
    
    //第一个参数为执行二进制的绝对路径,第二个参数为名称 也就是要传给第一个程序的argv[0]
    //test 程序是打印 main 函数参的程序
     
     #include <stdio.h>
     
     int main(int argc, char const *argv[])
     {
     
     for(int i=0;i<argc;i++)
     {
     printf("parameter %d is:%s\n",i,argv[i]);
     }
     
     return 0;
     }
   
     execl("/Users/wangrui/Desktop/test","say",NULL); //调用完后控制台 "parameter 0 is:say"
     *
     */
    
    
    FILE *f = fopen("/Users/wangrui/Desktop/stories.txt", "w");//会注册到id到descriptor表里
    
    if (!f) {
        error("Can't open stories.txt");
    }
    
    printf("father pid:%d\n",getpid());
    pid_t pid = fork();
    
    if (pid == -1) {
        error("Can't fork process");
    }
    
    if (pid == 0) {

        int fileDescriptor = fileno(f); //获取流descriptor表里的相关file流号
        
        printf("my pid:%d\n",getpid());
        printf("my father pid:%d\n",getppid());
        
        //sleep(10);
        
        //重定向
        if (dup2(fileDescriptor, 1) == -1 )
        {
            error("Can't redirect Standard Output");
        }
        

        if (execl("/usr/bin/say", "/usr/bin/say", "/Users/wangrui/Desktop/rssgossip.py", NULL) == -1)
        {
            error("Can't run script");
        }
    }
    
    int pid_status;
    
    pid_t waitPid = waitpid(pid, &pid_status, 0);
    
    if	( waitPid == -1) { //等待子进程完成
        
        printf("wait error pid :%d \n",getpid());
        error("Error Waiting for child process");
    }
    
    return 0;
}
